<?php 
require_once("app_fields.inc");
require_once("utils.inc");
require_once("DataBase.inc");

if (isset($_SESSION["debug"]) && $_SESSION["debug"]=="yes") {
	echo "<br/><br/>DEBUG:<br/>";
	echo "POST after view=";
	var_dump($_POST);
	echo "<br/><br/>";
}

$collapsable_counter = 0;
function collapsable_start($title, $expanded=false, $style="") {
	global $collapsable_counter;
	$id = $collapsable_counter++;
	echo "<table cellspacing=0 cellpadding=1 border=0 style='".$style."'>";
	echo "<tr style='background-color:#C0C0FF;font-weight:bold'><td style='border:1px solid #0000FF'>";
	echo "<img src='".$_SESSION["root_url"]."/images/".($expanded ? "expanded" : "collapsed").".gif' style='cursor:pointer;vertical-align:middle' hspace=2 vspace=0 onclick='expand_collapse(this,".$id.")'/>";
	echo $title;
	echo "</td></tr>";
	echo "<tr id='collapsable_".$id."' style='".($expanded ? "" : "position:absolute;visibility:hidden;top:-10000px;left:-10000px")."'><td style='border:1px solid #0000FF;border-top:0px'>";
	return $id;
}
function collapsable_end() {
	echo "</td></tr>";
	echo "</table>";
}
$checkbox_counter = 0;
function checkbox($name, $text, $checked, $oncheck="", $onuncheck="") {
	global $checkbox_counter;
	$id = $checkbox_counter++;
	echo "<span style='cursor:pointer' onclick=\"if (toggle_checkbox(".$id.")) { ".$oncheck." } else { ".$onuncheck." }\">";
	echo "<input type='hidden' name=\"".$name."\" value='".($checked?1:0)."' id='checkbox_input_".$id."'/>";
	echo "<img id='checkbox_img_".$id."' src='".$_SESSION["root_url"]."/images/".($checked?"checkmark.gif":"checkbox.gif")."' hspace=2 vspace=0 style='vertical-align:middle'/>";
	echo $text;
	echo "</span>";
	return $id;
}
?>

<script type='text/javascript'>
function element(id) {
	return document.all ? document.all[id] : document.getElementById(id);
}
function expand_collapse(img,id) {
	var tr = element('collapsable_'+id);
	if (tr.style.visibility == 'hidden') {
		img.src = '<?php echo $_SESSION["root_url"]?>/images/expanded.gif';
		tr.style.visibility = 'visible';
		tr.style.position = 'static';
	} else {
		img.src = '<?php echo $_SESSION["root_url"]?>/images/collapsed.gif';
		tr.style.visibility = 'hidden';
		tr.style.position = 'absolute';
		tr.style.top = '-10000px';
		tr.style.left = '-10000px';
	}
}
function expand_collapsable(id) {
	var tr = element('collapsable_'+id);
	var img = tr.childNodes[0].childNodes[0];
	img.src = '<?php echo $_SESSION["root_url"]?>/images/expanded.gif';
	tr.style.visibility = 'visible';
	tr.style.position = 'static';
}
function collapse_collapsable(id) {
	var tr = element('collapsable_'+id);
	var img = tr.childNodes[0].childNodes[0];
	img.src = '<?php echo $_SESSION["root_url"]?>/images/collapsed.gif';
	tr.style.visibility = 'hidden';
	tr.style.position = 'absolute';
	tr.style.top = '-10000px';
	tr.style.left = '-10000px';
}
function toggle_checkbox(id) {
	var input = element('checkbox_input_'+id);
	if (input.value == "1") {
		uncheck_checkbox(id); 
		return 0; 
	} else {
		check_checkbox(id);
		return 1;
	}
}
function check_checkbox(id) {
	var input = element('checkbox_input_'+id);
	var img = element('checkbox_img_'+id);
	input.value = "1";
	img.src = "<?php echo $_SESSION["root_url"]?>/images/checkmark.gif";
}
function uncheck_checkbox(id) {
	var input = element('checkbox_input_'+id);
	var img = element('checkbox_img_'+id);
	input.value = "0";
	img.src = "<?php echo $_SESSION["root_url"]?>/images/checkbox.gif";
}
</script>

<form name='fields_selection' action="applicants.php" method="post" onsubmit="return check_saved();" style='margin:0px;padding:0px;border-bottom:1px solid black'>
<input type='hidden' name='export' value='no'/>
<?php 
collapsable_start("Columns to display/edit");
?>
<input type='checkbox' name='include_excluded' <?php if (isset($_POST["include_excluded"])) echo "checked='checked' ";?>/> Include excluded applicants
 &nbsp; 
<input type='checkbox' name='can_remove' <?php if (isset($_POST["can_remove"])) echo "checked='checked' ";?>/> I want to be able to remove some applicants from the database
<br/>
<input type='hidden' name='sort' value='<?php if ($sort <> null) echo $sort;?>'/>
<?php 
foreach ($app_display_names as $section_name=>$fields) {
	collapsable_start($section_name, false, "float:left;margin: 3px");
	echo "<table border=0 cellspacing=1 cellpadding=1>";
	foreach ($fields as $field=>$name) {
		$f = new DisplayField($field, $name);
		echo "<tr><td>";
		$show_id = $checkbox_counter;
		$edit_id = $show_id + 1;
		checkbox($f->get_show_checkbox_name(), $f->display_name, is_shown($f), "", $f->is_editable() ? "uncheck_checkbox(".$edit_id.")" : "");
		echo "</td><td>";
		if ($f->is_editable()) {
			checkbox($f->get_edit_checkbox_name(), "Editable", has_edit($f), "check_checkbox(".$show_id.")");
		}
		echo "</td></tr>";
	}
	echo "</table>";
	collapsable_end();
}
collapsable_end();
?>

<script type='text/javascript'>
<?php
$max = -1;
foreach ($filters as $filter) {
	do {
		$id = $filter["id"];
		if ($id > $max) $max = $id;
		$filter = $filter["or"];
	} while ($filter <> null);
}
?>
var filter_counter = <?php echo ($max+1)?>;
function remove_filter(id) {
	var div = element('filter_div_'+id);
	var linked_id = null;
	if (document.forms['fields_selection'].elements['or_filter_'+id] != null)
		linked_id = document.forms['fields_selection'].elements['or_filter_'+id].value;
	if (div != null && div.parentNode != null) div.parentNode.removeChild(div);
	if (linked_id != null)
		filter_column_value_changed(linked_id);
}
function add_filter_by_column(column,value,or_link) {
	var div = document.createElement(or_link == null ? 'DIV' : 'SPAN');
	var id = filter_counter++;
	div.id = 'filter_div_'+id;
	var code = "";
	code += "<img src='<?php echo $_SESSION["root_url"]?>/images/trash.gif' hspace=2 vspace=0 style='vertical-align:middle;cursor:pointer' title='Remove this filter' onclick='remove_filter("+id+")'/>";
	code += "<input type='hidden' name='filter_"+id+"' value=''/>";
	code += "Column ";
	code += "<select id='filter_column_"+id+"' onchange='filter_column_changed("+id+")'>";
	code += "<option value=''> -- Please select a column to filter -- </option>";
	for (var section in fields_sections) {
		code += "<option value=''> &nbsp; &nbsp; -- "+section+" -- </option>";
		for (var field in fields_sections[section]) 
			code += "<option value=\""+field+"\""+(column==field ? " selected='selected'" : "")+">"+fields_sections[section][field]+"</option>";
	}
	code += "</select>";
	code += "<span id='filter_after_column_"+id+"'></span>";
	code += "<span id='filter_status_"+id+"'></span>";
	code += "<span id='filter_or_"+id+"'></span>";
	if (or_link != null) {
		code = " OR "+code;
		code += "<input type='hidden' name='or_filter_"+id+"' value='"+or_link+"'/>";
	}
	div.innerHTML = code;
	if (or_link == null) {
		var div_filters = element('filters');
		div_filters.appendChild(div);
	} else {
		var linked = element('filter_or_'+or_link);
		linked.appendChild(div);
	}
	if (column != null) filter_column_changed(id,value); else invalid_filter(id);
	if (or_link != null) {
		var b = element('button_filter_or_'+or_link);
		if (b != null && b.parentNode != null) b.parentNode.removeChild(b);
	}
	return id; 
}
function filter_column_changed(id,value) {
	var select_column = element('filter_column_'+id);
	var after_column = element('filter_after_column_'+id);
	while (after_column.childNodes.length > 0) after_column.removeChild(after_column.childNodes[0]);
	if (select_column.value == '') { invalid_filter(id); return; }
	switch (fields_type[select_column.value]) {
	case "int":
	case "double":
	case "date":
	case "time":
		var op = null, operand = null;
		if (value!=null) {
			if (value[0] == ' ') { op = "="; operand = value; }
			else {
				var i = value.indexOf("'");
				op = value.substring(0,i);
				operand = value.substring(i);
			}
		}
		after_column.innerHTML = "value is "+get_operator_code(id,op);
		filter_column_operator_changed(id,operand);
		break;
	default:
		var code = get_possible_value_combobox_code(id,select_column.value,value);
		if (code == null) { invalid_filter(id,'No applicant have this column set'); return; }
		after_column.innerHTML = "value = "+code;
		if (value == null) invalid_filter(id); else filter_column_value_changed(id);
	}
}
function get_operator_code(id,op) {
	var code = "<select id='filter_column_operator_"+id+"' onchange='filter_column_operator_changed("+id+")'>";
	code += "<option value='='"+(op == null || op == "=" ? " selected='selected'" : "")+">=</option>";
	code += "<option value='&lt;'"+(op == "<" ? " selected='selected'" : "")+">&lt;</option>";
	code += "<option value='&lt;='"+(op == "<=" ? " selected='selected'" : "")+">&lt;=</option>";
	code += "<option value='&gt;'"+(op == ">" ? " selected='selected'" : "")+">&gt;</option>";
	code += "<option value='&gt;='"+(op == ">=" ? " selected='selected'" : "")+">&gt;=</option>";
	code += "</select>";
	code += "<span id='after_operator_"+id+"'></span>";
	return code;
}
function filter_column_operator_changed(id,operand) {
	var select_column = element('filter_column_'+id);
	var field = select_column.value;
	var operator = element('filter_column_operator_'+id);
	var op = operator.value;
	var after_operator = element('after_operator_'+id);
	if (op == "=") {
		after_operator.innerHTML = get_possible_value_combobox_code(id,field,"="+operand);
	} else {
		after_operator.innerHTML = get_input_value_code(id,field,operand);
	}
	if (operand != null) filter_column_value_changed(id); else invalid_filter(id);
}
function get_possible_value_combobox_code(id,field,selected) {
	//if (possible_values[field] == null) return null;
	var code = "<select id='filter_column_value_"+id+"' onchange='filter_column_value_changed("+id+")'>";
	code += "<option value=''> -- Please select -- </option>";
	code += "<option value=' IS NULL'"+(selected=="= IS NULL" || selected==" IS NULL" ? " selected='selected'" : "")+">&lt;empty&gt;</option>";
	code += "<option value=' IS NOT NULL'"+(selected=="= IS NOT NULL" || selected==" IS NOT NULL" ? " selected='selected'" : "")+">&lt;any, not empty&gt;</option>";
	if (possible_values[field] != null) {
		var values = possible_values[field];
		for (var v in values)
			code += "<option value=\"='"+v+"'\""+(selected=="='"+v+"'" ? " selected='selected'" : "")+">"+values[v]+"</option>";
	}
	code += "</select>";
	return code;
}
function get_input_value_code(id,field,value) {
	if (value != null && value[0] == "'") value = value.substring(1,value.length-1);
	switch (fields_type[field]) {
	case "int": return "<input id='filter_column_value_"+id+"' type='text' size=10 maxlength=10 onkeydown='if (!validate_int(this,event)) return false; filter_column_value_changed("+id+");return true' onkeyup='filter_column_value_changed("+id+");' onchange='filter_column_value_changed("+id+");' value=\""+(value != null ? value : "")+"\"/>"; break;
	case "double": return "<input id='filter_column_value_"+id+"' type='text' size=10 maxlength=10 onkeydown='if (!validate_double(this,event)) return false; filter_column_value_changed("+id+");return true' onkeyup='filter_column_value_changed("+id+");' onchange='filter_column_value_changed("+id+");' value=\""+(value != null ? value : "")+"\"/>"; break;
	case "date": return "<input id='filter_column_value_"+id+"' name='__date__filter_column_value_"+id+"' type='text' size=10 maxlength=10 onchange='filter_column_value_changed("+id+")' readonly='readonly' onclick=\"displayDatePicker('__date__filter_column_value_"+id+"')\" value=\""+(value != null ? value : "")+"\"/>"; break;
	case "time": return "<input id='filter_column_value_"+id+"' type='text' size=5 maxlength=5 onkeyup='validate_time(this);filter_column_value_changed("+id+");' onchange='filter_column_value_changed("+id+");' value=\""+(value != null ? value : "")+"\"/>"; break;
	}
	return "invalid field type!";
}
function filter_column_value_changed(id) {
	var field = element('filter_column_'+id).value;
	var value = element('filter_column_value_'+id).value;
	var select_op = element('filter_column_operator_'+id);
	var operator = select_op == null ? "" : select_op.value;
	if (operator == "=") operator = "";
	if (operator != "") value = "'"+value+"'";
	var input = document.forms['fields_selection'].elements['filter_'+id];
	if (value == '') {
		input.value = '';
		invalid_filter(id);
	} else {
		input.value = field+operator+value;
		valid_filter(id);
	}
}
function invalid_filter(id,msg) {
	var status = element('filter_status_'+id);
	status.innerHTML = "<img src='<?php echo $_SESSION["root_url"]?>/images/error.png' hspace=2 vspace=0 style='vertical-align:middle'/> <span style='color:red'>"+(msg==null?"Please complete this filter":msg)+"</span>";
}
function valid_filter(id) {
	var status = element('filter_status_'+id);
	var code = "&nbsp;<img src='<?php echo $_SESSION["root_url"]?>/images/ok.png' style='vertical-align:bottom'/>";
	var filter_or = element('filter_or_'+id);
	if (filter_or.childNodes.length == 0)
		code += " <button id='button_filter_or_"+id+"' onclick='filter_or("+id+");return false' style='margin:0px;padding:0px;font-size:9pt'>Or...</button>";
	status.innerHTML = code;
}
function filter_or(id) {
	add_filter_by_column(null,null,id);
}
var o;
var fields_sections = new Object();
<?php
foreach ($app_display_names as $section_name=>$fields) {
	echo "o = new Object();";
	echo "fields_sections[\"".$section_name."\"] = o;\n";
	foreach ($fields as $field=>$name) {
		$f = new DisplayField($field, $name);
		echo "o[\"".$f->get_show_checkbox_name()."\"] = \"".$f->display_name."\";\n";
	}
}
?>
var fields_type = new Object();
var possible_values = new Object();
<?php
foreach ($app_display_names as $section_name=>$fields) {
	foreach ($fields as $field=>$name) {
		$f = new DisplayField($field, $name);
		$possibilities = null;
		$table = $f->table;
		$field = $f->field;
		$query = "";
		$joins = "";
		$groups = "";
		$order_by = $f->table.".".$f->field;
		$table = $f->table;
		$last_field = $f->field;
		$type = explode('#',$app_fields[$table][$field]);
		if ($f->indirection <> null) {
			$indirection = $f->indirection;
			do {
				$i = strpos($indirection, "#");
				if ($i > 0) {
					$current_indirection = substr($indirection, 0, $i);
					$indirection = substr($indirection, $i+1);
				} else {
					$current_indirection = $indirection;
					$indirection = null;
				}
				$indirect_table = $type[1];
				$indirect_field = $type[2];
				$query .= ",".$indirect_table.".".$current_indirection;
				$order_by = $indirect_table.".".$current_indirection;
				if ($indirection<>null) $groups .= " GROUP BY ".$indirect_table.".".$current_indirection;
				$joins .= " LEFT JOIN ".$indirect_table." ON ".$indirect_table.".".$indirect_field."=".$table.".".$field;
				$table = $indirect_table;
				$field = $current_indirection;
				$last_field = $current_indirection;
				$type = explode('#',$app_fields[$table][$field]);
			} while ($indirection <> null);
		}
		if ($type[0] == "date" || $type[0] == "time") {
			$query = "SELECT DISTINCT ".$field." FROM ".$table." ORDER BY ".$field;
		} else {
			$query = "SELECT DISTINCT ".$f->table.".".$f->field.$query;
			$query .= " FROM ".$f->table;
			$query .= $joins;
			$query .= $groups;
			$query .= " ORDER BY ".$order_by;
		}
		
		//$type = explode("#", $app_fields[$table][$field]);
		echo "fields_type[\"".$f->get_show_checkbox_name()."\"] = \"".$type[0]."\";\n";
		$from_db = false;
		switch ($type[0]) {
			case "bool": $possibilities = array(1=>"Yes", 0=>"No"); break;
			case "string":
				if (count($type)==3 && substr($type[2],0,1)<>"*") {
					$list = explode(",",$type[2]);
					$possibilities = array();
					foreach ($list as $s) $possibilities[$s] = $s;
				} else $from_db = true;
				break;
			case "int":
				if (count($type)==3) {
					$min_max = explode(",",$type[1]);
					$min = intval($min_max[0]);
					$list = explode(",",$type[2]);
					$possibilities = array();
					for ($i = 0; $i < count($list); $i++)
						$possibilities["".($min+$i)] = $list[$i];
				}
				// not from db;
				break;
			case "double": /* not from db */ break;
			default: $from_db = true; break;
		}
		if ($from_db) {
			$result = DataBase::query($query);
			$possibilities = array();
			if ($result <> false) {
				if ($type[0] == "date" || $type[0] == "time")
					$r = $last_field;
				else
					$r = $f->field;
				foreach ($result as $row) {
					if ($row[$r] == null || strlen(trim($row[$r]))==0) continue;
					$possibilities[$row[$r]] = $row[$last_field]; 
				}
			}
		}
		if ($possibilities<>null && count($possibilities)>0) {
			echo "o = new Object();";
			foreach ($possibilities as $value=>$display)
				echo "o[\"".str_replace("\n", "\\n", $value)."\"] = \"".str_replace("\n", "\\n", $display)."\";";
			echo "possible_values[\"".$f->get_show_checkbox_name()."\"] = o;\n";
		}
	}
}
?>
</script>

<?php
$filter_collapsable_id = collapsable_start("Filters", count($filters)>0, "margin-top:2px;margin-bottom:1px");
echo "<div id='filters'>";
echo "</div>";
echo "<button onclick='add_filter_by_column();return false'>Add a filter by column</button>";
collapsable_end();
?>
<button type='submit'><img src='<?php echo $_SESSION["root_url"]?>/images/refresh.gif' hspace=2 vspace=0 style='vertical-align:bottom'/>Refresh</button> &nbsp; 
<button type='submit' onclick="document.forms['fields_selection'].elements['export'].value = 'excel';document.forms['fields_selection'].submit();document.forms['fields_selection'].elements['export'].value = 'no';return false;">
<img src='<?php echo $_SESSION["root_url"]?>/images/excel.gif' hspace=2 vspace=0 style='vertical-align:bottom'/>
Export to Excel
</button>
<?php 
if (isset($_POST["additional_code"])) echo "<input type='hidden' name='additional_code' value=\"".text2html($_POST["additional_code"])."\"/>";
$zoom = isset($_POST["zoom"]) ? $_POST["zoom"] : 10;
if ($zoom < 5) $zoom = 5;
if ($zoom > 20) $zoom = 20;
?>
<input type='hidden' name='zoom' value='<?php echo $zoom;?>'/>
</form>

<script type='text/javascript'>
function toggle_filter(field) {
	expand_collapsable(<?php echo $filter_collapsable_id?>);
	var found = false;
	for (var i = 0; i < filter_counter; ++i) {
		var f = element('filter_column_'+i);
		if (f == null) continue;
		f = f.value;
		if (f == field) {
			remove_filter(i);
			found = true;
		}
	}
	if (!found) {
		add_filter_by_column(field);
	}
}
var filter_id;
<?php 
foreach ($filters as $filter) {
	switch ($filter["type"]) {
		case "column":
			echo "filter_id = add_filter_by_column(\"field__".$filter["field"]."\",\"".$filter["condition"]."\");\n";
			while ($filter["or"]<>null) {
				$filter = $filter["or"];
				echo "filter_id = add_filter_by_column(\"field__".$filter["field"]."\",\"".$filter["condition"]."\",filter_id);\n";
			}
			break;
	}
}
?>
</script>